package com.epoint.mobileoa.ui.mail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.bizlogic.mobileoa.GetMailListTask;
import com.epoint.mobileoa.model.MailList;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.DateHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;
import android.text.Spanned;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author liyc
 * @time 2012-2-4 上午12:21:12
 * @annotation 收件箱
 */
public class MailBoxReceiveView extends SuperView{

	private ListView lv;

	private int shownum = 20;//每页显示数量

	private int pagenum = 1;//第几页

	private int allmailnums;//所有邮件数量

//	private Button load_bt;//加载中的文本
	private LinearLayout foot;

	private MyAdapter adapter = new MyAdapter();

	//查询条件
	private String sjFrom = "",sjTo = "",bt = "",sjr = "";

	@Override
	public void initControls() {
		lv = (ListView) findViewById(R.id.lv_mailstyle);
		lv.setOnItemClickListener(this);

		//查询按钮
		if("1".equals(PropertiesHelp.getProperty(this,"FileAttachSearch"))){
//			top_right_bt.setBackgroundResource(R.drawable.top_right_search"));
			top_right_bt.setText("查找");
			top_right_bt.setVisibility(View.VISIBLE);
			top_right_bt.setOnClickListener(this);
		}

		addFoot();

		lv.setAdapter(adapter);

		getData(pagenum,shownum);

		lv.setVisibility(View.INVISIBLE);
	}

	public void addFoot(){
		TextView load_bt = new TextView(this);
		load_bt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		load_bt.setText("更多...");
		load_bt.setGravity(Gravity.CENTER);
		foot = new LinearLayout(this);
		foot.addView(load_bt, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		foot.setGravity(Gravity.CENTER);
		lv.addFooterView(foot);
		registerForContextMenu(lv);
	}

	public void getData(int pagenum, int shownum){
		top_pb.setVisibility(View.VISIBLE);
		HashMap<String,Object> param=new HashMap<String,Object>();
		param.put("pagenum", pagenum);
		param.put("shownum", shownum);
		param.put("sjfrom", sjFrom);
		param.put("sjto", sjTo);
		param.put("bt", bt);
		param.put("sjr", sjr);
		Task task = new GetMailListTask(this, param);
		MainService.addTask(task);
	}

	@Override
	public void onClick(View v) {
		if(v==top_right_bt){
			LayoutInflater inflater = LayoutInflater
					.from(this);
			LinearLayout ll = (LinearLayout) inflater.inflate(
					R.layout.mailsearchlayout, null);

			final EditText etSjFrom = (EditText) ll.findViewById(R.id.etSjFrom);
			final EditText etSjTo = (EditText) ll.findViewById(R.id.etSjTo);
			final EditText etTitle = (EditText) ll.findViewById(R.id.etTitle);
			final EditText etSjr = (EditText) ll.findViewById(R.id.etSjr);

			etSjFrom.setText(sjFrom);
			etSjTo.setText(sjTo);
			etTitle.setText(bt);
			etSjr.setText(sjr);
			
			etSjFrom.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AlertHelp.showDatePickDialogWithCancel(MailBoxReceiveView.this, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							etSjFrom.setText(year + "-" + DateHelp.switchDay((monthOfYear+1)) + "-" + DateHelp.switchDay(dayOfMonth));
						}
					},null);
				}
			});

			etSjTo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AlertHelp.showDatePickDialog(MailBoxReceiveView.this, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							etSjTo.setText(year + "-" + DateHelp.switchDay((monthOfYear+1)) + "-" + DateHelp.switchDay(dayOfMonth));
						}
					},null);
				}
			});

			new AlertDialog.Builder(this)
			.setIcon(R.drawable.epoint2)
			.setTitle("收件箱搜索")
			.setView(ll)
			.setPositiveButton("确定",new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					sjFrom = etSjFrom.getText().toString();
					sjTo = etSjTo.getText().toString();
					bt = etTitle.getText().toString();
					sjr = etSjr.getText().toString();

					pagenum = 1;

					getData(pagenum, shownum);
				}
			})
			.setNegativeButton("取消", null)
			.create()
			.show();
		}
	}

	private List<MailList> alllist = new ArrayList<MailList>();
	@Override
	public void refresh(Object... param) {
		top_pb.setVisibility(View.INVISIBLE);
		if(param[0].toString().equals(MainService.NORMAL)){

			lv.setVisibility(View.VISIBLE);

			String bs = param[1].toString();
			allmailnums = Integer.parseInt(StringHelp.getXMLAtt(bs, "allnum"));
			String content =  "<root>"+StringHelp.getXMLAtt(bs, "getmails")+"</root>";
			List<MailList> maillist = GetMailListTask.XmlAnalysis(content);

			if(maillist.size()==0){
				ToastHelp.showToastCommon(this, "数据加载完毕");
			}

			if(pagenum==1){
				alllist.clear();
			}

			for(MailList m:maillist){
				alllist.add(m);
			}

			adapter.notifyDataSetChanged();

		}

	}

	@Override
	public int getLayoutInt() {
		return R.layout.layout_mailstyle;
	}


	@Override
	public String setTitle() {
		return getString(R.string.sjx);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(position==alllist.size()){
			pagenum ++;
			getData(pagenum, shownum);
			return;
		}
		Intent it = new Intent(this,MailDetailView.class);
		it.putExtra("pagetitle", "邮件详情");
		it.putExtra("mailtitle", alllist.get(position).title);
		it.putExtra("mailguid", alllist.get(position).guid);
		it.putExtra("mailsender", alllist.get(position).msgFrom);
		it.putExtra("mailtime", alllist.get(position).time);
		it.putExtra("hasattach", alllist.get(position).attachment);
		it.putExtra("intenttype", "sjx");
		MailDetailView.pagetype = 0;

		//消除状态栏的Notification
		if(alllist.get(position).status.equals("0")){
			NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			manager.cancel(MainService.MAIL_NOTIFICATION_FLAG);
		}
		startActivityForResult(it, 1001);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1001){
			switch (resultCode) {
			case RESULT_OK:
				String openmailguid = data.getStringExtra("mailguid");
				for(int i=0;i<alllist.size();i++){
					if(alllist.get(i).guid.equals(openmailguid)){
						MailList ml = alllist.get(i); 
						ml.status = "1";
						alllist.set(i, ml);
					}
				}
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	
		super.onActivityResult(requestCode, resultCode, data);
	}

	class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return alllist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				LayoutInflater mInflater = LayoutInflater.from(MailBoxReceiveView.this);
				convertView = mInflater.inflate(R.layout.epointxmlist, null);
				holder.ml_mailimg = (ImageView) convertView
						.findViewById(R.id.ml_mailimg);
				holder.ml_attach = (ImageView) convertView
						.findViewById(R.id.ml_attach);
				holder.ml_mailtitle = (TextView) convertView
						.findViewById(R.id.ml_mailtitle);
				holder.ml_sandt = (TextView) convertView
						.findViewById(R.id.ml_sandt);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			String sender = alllist.get(position).msgFrom;
			String time = alllist.get(position).time;
			Spanned h = Html.fromHtml("<font color=red>" + sender
					+ "</font>&nbsp;&nbsp;" + "<font color="+getYGColor()+">" + time
					+ "</font>");
			holder.ml_sandt.setText(h);

			holder.ml_mailtitle.setText(alllist.get(position).title);
			setTextViewFontColor(holder.ml_mailtitle);
			if(alllist.get(position).status.equals("0")){
				holder.ml_mailimg.setBackgroundResource(R.drawable.view_folder_unread);
			}
			else{
				holder.ml_mailimg.setBackgroundResource(R.drawable.mailopen2);
			}

			if(alllist.get(position).attachment.equals("1")){
				holder.ml_attach.setVisibility(View.VISIBLE);
				holder.ml_attach.setBackgroundResource(R.drawable.mailattach2);
			}
			else{
				holder.ml_attach.setVisibility(View.GONE);
			}


			return convertView;
		}

	}

	public class ViewHolder {
		public ImageView ml_mailimg;
		public ImageView ml_attach;
		public TextView ml_mailtitle;
		public TextView ml_sandt;
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}